#!/usr/bin/perl -w
use strict;
use Includes;
use CGI qw/:standard *table *div -nosticky/;
use CGI::Pretty qw/ :html3 /;
use CGI::Cookie;

# Some variables 
my $c = new CGI;
my ($password,$username) = ($c->param('password'),$c->param('username'));
# Some paths
my $DBFILE	= "users.sql";

my $SUCCESS = 0;
my $cookie;
my $status = &status;


# Check to see if we succeeded 
if($SUCCESS){
	Includes::my_log('task1','info',"Completed by: %s",$username);
	$cookie = new CGI::Cookie(-name=>'username',-value=>$username);
}

# Make the basic HTML and form 
print header(-type => 'text/html',-cookie=>[$cookie]),
			Includes::get_html("Welcome"),
			div({id=>'main',class=>'rounded'},
					Includes::get_banner(),
					$status,
					&form,
					),
			end_html();

### Functions ###

# Determine if the user can log in
sub status(){
	my $string;
	if( param && $c->param('action') eq 'Login'){
		use Switch;
		switch(&authorized($username,$password)){
			case	"NO_USER"		{ $string = "Bad username/password" }
			case	"NOT_ADMIN"	{ $string = span("Only system administrators may view this page.",br,"Please contact your local HR representative if you need access") }
			else							{ $string = span("You've successfully completed task #1",br,"Your account will now be deleted"); $SUCCESS = 1;
			}
		}
	}
	return $string ? div({id=>'status',class=>$SUCCESS?'success':'error'},$string) : '';
}

# Create the form
sub form(){
	return 
			start_form("POST"),
			fieldset(
				legend("Enter Login Information",
					p(label({for=>'username'},"Name"),textfield('username')),
					p(label({for=>'password'},"Password"),password_field('password')),
					p({class=>'submit'},submit('action','Login'))
					)
				),
			end_form,
			div({id=>'register',class=>'center'},
				a({href=>'register.cgi'},"Don't have a login?"));
}

sub authorized($$){
	my($retval,$username,$password) = (0,@_);
# Username and password must be alphanumerics
	if(!($username =~ /^[a-zA-Z0-9]{1,16}$/ && $password =~ /^[a-zA-Z0-9]{1,16}$/)){ 
		$retval = "NO_USER";
	}else{
		my $dbh = Includes::connect($DBFILE);
		my $sth = $dbh->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
		$sth->bind_param(1,$username);
		$sth->bind_param(2,$password);
		$sth->execute or die $sth->errstr;
		my @vals = $sth->fetchrow_array;
		if($sth->rows){
			if($vals[2] != 1){
				$retval = "NOT_ADMIN";
			}
			my $del = $dbh->prepare("DELETE FROM users WHERE username = ? AND password = ?");
			$del->bind_param(1,$username);
			$del->bind_param(2,$password);
			$del->execute or die $sth->errstr;
		}else{
			$retval = "NO_USER";
		}
	}
	return $retval;
}
